<?php

/**
 * 商品搜索
 */

namespace app\mall\common;

class SearchCommon extends \app\base\common\SiteCommon {

    protected $pageLimit = 10;

    protected function index() {

        $name = request('', 'keyword');
        $name = str_len(html_clear(urldecode($name)), 10, false);
        if (empty($name)) {
            $this->error('请输入搜索关键词!');
        }

        $this->pageInfo['name'] = $name . ' - 搜索';
        $this->setMeta($name . ' - 搜索');
        $this->setCrumb([
            [
                'name' => $name,
                'url' => url()
            ]
        ]);

        $pageLimit = 15;
        $service = target('shop/Filter', 'service');
        $classId = request('get', 'class_id', 0, 'intval');

        $filterWhere = [];
        if ($classId) {
            $filterWhere['A.class_id'] = $classId;
        }
        $filterWhere['_sql'] = 'B.title like "%' . $name . '%"';
        $data = $service->getData('mall', $filterWhere, ['keyword' => $name, 'class_id' => $classId]);

        $filter = $data['filter'];
        $where = $data['where'];
        $order = $data['order'];

        $priceList = $service->getPriceData($filter['ids']);
        $brandList = $service->getBrandData($filter['ids']);

        $orderList = $service->getOrderData();

        $model = target('mall/Mall');

        $classList = [];
        if ($filter['ids']) {
            $data = $model->field(['class_id'])->where(['_sql' => 'mall_id in (' . $filter['ids'] . ')'])->limit(0)->select();
            $data = array_unique($data);
            $classIds = [];
            foreach ($data as $vo) {
                $classIds[] = $vo['class_id'];
            }
            $classList = target('mall/MallClass')->loadList([
                '_sql' => 'class_id in (' . implode(',', $classIds) . ')'
            ]);
        }
        if ($where) {
            $count = $model->countList($where);
            $pageData = $this->pageData($count, $pageLimit, $filter['urlParam']);
            $list = $model->loadList($where, $pageData['limit'], $order);
        } else {
            $pageData = [];
            $list = [];
        }


        $this->assign('attrList', $filter['attrList']);
        $this->assign('classList', $classList);
        $this->assign('brandList', $brandList);
        $this->assign('priceList', $priceList);
        $this->assign('orderList', $orderList);
        $this->assign('urlParam', $filter['urlParam']);
        $this->assign('page', $pageData['html']);
        $this->assign('pageList', $list);
        $this->siteDisplay('mall_search');
    }


}